package com.crane.oss.web.interceptor;

import com.crane.common.core.dto.Response;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zhenxing.pi
 */
@ControllerAdvice(basePackages = "com.crane.oss.web.controller")
public class XssResponseBodyAdvice implements ResponseBodyAdvice<Response> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        return true;
    }

    @Override
    public Response beforeBodyWrite(Response body, MethodParameter returnType, MediaType selectedContentType,
                                    Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                    ServerHttpResponse response) {
        // 修改响应头
        response.getHeaders().setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE));
        response.getHeaders().set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        response.getHeaders().set("Access-Control-Allow-Headers",
                "Origin,Accept,x-requested-with,content-type,X-AUTH-SESSION,Content-Security-Policy,X-Content-Type-Options,X-XSS-Protection");
        response.getHeaders().set("Access-Control-Expose-Headers",
                "X-AUTH-SESSION,Content-Security-Policy,X-Content-Type-Options,X-XSS-Protection");
        response.getHeaders().set("Access-Control-Max-Age", "3600");
        response.getHeaders().set("Content-Security-Policy",
                "script-src 'self'; object-src 'none'; style-src cdn.example.org third-party.org; child-src https:");
        response.getHeaders().set("X-Content-Type-Options", "nosniff");
        response.getHeaders().set("X-XSS-Protection", "1; mode=block");

        return body;
    }


}
